package main

import (
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"log"
	"math/rand"
	"net/http"
	"os"
	"time"
)

var (
	requestLatency = prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Name: "http_request_latency_seconds",
			Help: "Request latency distribution.",
		},
		[]string{"path"},
	)
)

func main() {
	// 注册度量指标
	prometheus.MustRegister(requestLatency)
	//暴露监控指标采集接口
	http.Handle("/metrics", promhttp.Handler())
	http.HandleFunc("/healthz", recordTime(healthz))
	http.HandleFunc("/", recordTime(index))
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Server start....")
}

func recordTime(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 开始时间
		start := time.Now()
		// 调用下一个处理器
		next(w, r)
		//结束时间
		duration := time.Since(start).Seconds()
		// 记录延时度量指标，并设置标签值为请求路径
		requestLatency.With(prometheus.Labels{"path": r.URL.Path}).Observe(duration)
	}
}

func healthz(w http.ResponseWriter, r *http.Request) {
	//返回200状态码
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "OK")
}

func index(w http.ResponseWriter, r *http.Request) {
	//添加0-2秒的延时
	time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
	header := r.Header
	for key, _ := range header {

		w.Header().Add(key, header.Get(key))
	}
	//加个response header测试下
	w.Header().Add("password", "killer")
	//读取系统环境变量version
	w.Header().Add("VERSION", os.Getenv("VERSION"))
	//返回200状态码
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "OK")
}
